package com.roobtyan.todomemback.controller;

import com.roobtyan.todomemback.entity.MemCard;
import com.roobtyan.todomemback.service.CardService;
import com.roobtyan.todomemback.utils.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@Controller
@CrossOrigin
@RequestMapping("/card")
public class CardController {
    @Resource
    private CardService cardService;

    @GetMapping("/todayCards")
    @ResponseBody
    public Object getTodayCardList() {
        return cardService.getTodayCard();
    }

    @GetMapping("/getCard")
    @ResponseBody
    public Object getCard(int dir1Id) {
        return cardService.getCardListByDir1Id(dir1Id);
    }

    @PostMapping("/insert")
    @ResponseBody
    boolean insertCard(@RequestBody MemCard memCard) {
        memCard.setId(StringUtil.generateShortUuid());
        memCard.setCreateTime(new Date());
        memCard.setReviewTime(new Date());
        memCard.setTimeInterval(0); // 初次学习，复习间隔设为0
        memCard.setReviewTimes(1);  // 第一次复习（学习）
        memCard.setNextReviewTime(cardService.computeReviewDate(1));  // 设置下次复习时间为第二天
        memCard.setStatus(1);   // 0.停止复习 1.正在复习 2.复习完成

        return cardService.insertSelectiveCard(memCard);
    }

    @GetMapping("/delete")
    @ResponseBody
    boolean deleteCard(String cardId) {
        return cardService.deleteSelectiveCard(cardId);
    }

    @GetMapping("/review")
    @ResponseBody
    boolean reviewCard(String cardId) {
        MemCard card = cardService.getCardById(cardId);
        card.setReviewTimes(card.getReviewTimes() + 1);   // 增加一次复习次数
        card.setReviewTime(new Date());
        int reviewStep = cardService.computeReviewStep(card.getTimeInterval());
        if (reviewStep != 0) {
            card.setTimeInterval(reviewStep);    // 计算本次复习间隔
            card.setNextReviewTime(cardService.computeReviewDate(card.getTimeInterval()));  // 计算下一次复习的日期
        } else {
            card.setStatus(2);  // 下次复习时间为0的时候，表示已经完成复习任务
        }
        return cardService.updateSelectiveCard(card);
    }

    @GetMapping("/forgot")
    @ResponseBody
    boolean forgotCard(String cardId) {
        MemCard card = cardService.getCardById(cardId);
        card.setReviewTime(new Date());
        card.setReviewTimes(card.getReviewTimes() + 1);   // 增加一次复习次数
        card.setNextReviewTime(cardService.computeReviewDate(card.getTimeInterval() + 1));

        return cardService.updateSelectiveCard(card);
    }

    @PostMapping("/update")
    @ResponseBody
    boolean updateCard(MemCard memCard) {
        return cardService.updateSelectiveCard(memCard);
    }
}
